package com.gy.hsim.bservice.userGroupingManagement.restful;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.org.eclipse.jdt.core.IField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gy.hsim.bservice.framework.bean.QueryVerifyReponse;
import com.gy.hsim.bservice.framework.enums.MessageResultEnum;
import com.gy.hsim.bservice.framework.restful.BaseController;
import com.gy.hsim.bservice.message.bean.Message;
import com.gy.hsim.bservice.userGroupingManagement.bean.Team;
import com.gy.hsim.bservice.userGroupingManagement.service.TeamService;

/**
 * 
 * @ClassName: TeamController 
 * @Description: 好友分组 Controller
 * @author quanrj 
 * @date 2015-12-11 上午09:57:19
 */
@Controller
@RequestMapping("/team")
public class TeamController extends BaseController {
	private static final Logger log = LoggerFactory
			.getLogger(Team.class);
	
	@Autowired
	private TeamService teamService;
	
	/**
	 * 添加群URL: http://localhost:8099/hsim-bservice/team/addTeam
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/addTeam",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse addTeam(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		QueryVerifyReponse resp = new QueryVerifyReponse();
		try {
			//获取前端传过来的数据
			JSONObject object = (JSONObject)request.getAttribute("object");
			Team team = JSON.toJavaObject(object, Team.class);
			System.out.println("【接收到的json】：" + object);
			log.debug("【接收到的json】：" + object);
			
			//不鉴权时获取前端传过来的数据
			/*InputStream is = null;
			is = request.getInputStream();			
			byte bytes[] = new byte[request.getContentLength()];
			is.read(bytes);
			//得到请求中的内容区数据（以CharacterEncoding解码）
			String jsonStr = new String(bytes, "utf-8");
			System.out.println("【接收到的json】：" + jsonStr);
			log.debug("【接收到的json】：" + jsonStr);

			Team team = JSON.toJavaObject(JSON.parseObject(jsonStr), Team.class);*/
			
			//组装teamId
			String teamCreator = team.getTeamCreator();
			Date now = new Date(); 
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");//可以方便地修改日期格式
			String dateStr = dateFormat.format(now);
			String teamId = new String(teamCreator.substring(0,11) + dateStr);
			team.setTeamId(teamId);
			
			//校验好友创建分组数不能超过上限
			boolean teamsUserCreateCheck = teamService.getTotalTeamsUserCreateCheck(team);
			if(!teamsUserCreateCheck){
				resp.setRetCode(MessageResultEnum.TEAMCREATE_LIMIT.getRetCode());
				resp.setMessage(MessageResultEnum.TEAMCREATE_LIMIT.getMessage());
				return resp;
			}
			
			//校验好友分组名称不能重复
			boolean teamNameCheck = teamService.teamNameCheck(team);
			if(!teamNameCheck){
				resp.setRetCode(MessageResultEnum.TEAMNAME_DUPLICATE.getRetCode());
				resp.setMessage(MessageResultEnum.TEAMNAME_DUPLICATE.getMessage());
				return resp;
			}
			
			teamService.addTeam(team);
			
			Team  newTeam = new Team();
			newTeam.setTeamId(teamId);
			newTeam.setTeamName(team.getTeamName());
			
			List<Team> teamlist = new ArrayList<Team>();
			teamlist.add(newTeam);
			
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			resp.setRows(teamlist);
			System.out.println("【添加分组成功】：" + team.getTeamId());
			log.debug("【添加分组成功】：" + team.getTeamId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
		}
       return resp;
	}
	
	/**
	 * 根据用户ID查询分组信息URL: http://localhost:8099/hsim-bservice/team/queryTeamInfoByUserId
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryTeamInfoByUserId",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse queryTeamInfoByUserId(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		QueryVerifyReponse resp = new QueryVerifyReponse();
		try {
			//获取前端传过来的数据
			JSONObject object = (JSONObject)request.getAttribute("object");
			Team team = JSON.toJavaObject(object, Team.class);
			System.out.println("【接收到的json】：" + object);
			log.debug("【接收到的json】：" + object);
			
			//不鉴权时获取前端传过来的数据
			/*InputStream is = null;
			is = request.getInputStream();			
			byte bytes[] = new byte[request.getContentLength()];
			is.read(bytes);
			//得到请求中的内容区数据（以CharacterEncoding解码）
			String jsonStr = new String(bytes, "utf-8");
			System.out.println("【接收到的json】：" + jsonStr);
			log.debug("【接收到的json】：" + jsonStr);

			Team team = JSON.toJavaObject(JSON.parseObject(jsonStr), Team.class);*/
			
			List<Team> teamInfoList = new ArrayList<Team>();
			teamInfoList = teamService.queryTeamInfoByUserId(team);
			//添加一个黑名单分组到teamInfoList中
			Team blacklistedTeam = new Team();
			blacklistedTeam.setTeamId("blacklisted");
			blacklistedTeam.setTeamName("黑名单");
			teamInfoList.add(blacklistedTeam);
			
			int totalRows = teamInfoList.size();
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			resp.setRows(teamInfoList);
			resp.setTotalRows(totalRows);
			System.out.println("【查询分组信息成功】：" + team.getTeamCreator());
			log.debug("【查询分组信息成功】：" + team.getTeamCreator());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
		}
       return resp;
	}
	
	/**
	 * 查询好友是否已经把用户拉黑URL: http://localhost:8099/hsim-bservice/team/queryFriendSetUserBlacklisted
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryFriendSetUserBlacklisted",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse queryFriendSetUserBlacklisted(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		QueryVerifyReponse resp = new QueryVerifyReponse();
		try {
			//获取前端传过来的数据
			JSONObject object = (JSONObject)request.getAttribute("object");
			Team team = JSON.toJavaObject(object, Team.class);
			System.out.println("【接收到的json】：" + object);
			log.debug("【接收到的json】：" + object);
			
			//不鉴权时获取前端传过来的数据
			/*InputStream is = null;
			is = request.getInputStream();			
			byte bytes[] = new byte[request.getContentLength()];
			is.read(bytes);
			//得到请求中的内容区数据（以CharacterEncoding解码）
			String jsonStr = new String(bytes, "utf-8");
			System.out.println("【接收到的json】：" + jsonStr);
			log.debug("【接收到的json】：" + jsonStr);

			Team team = JSON.toJavaObject(JSON.parseObject(jsonStr), Team.class);*/
			
			int blacklistedCount = teamService.queryFriendSetUserBlacklisted(team);
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			resp.setTotalRows(blacklistedCount);
			System.out.println("【查询是否被好友拉黑成功】 数量 ：" + blacklistedCount);
			log.debug("【查询是否被好友拉黑成功】  数量 ：" + blacklistedCount);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
		}
       return resp;
	}
	
	/**
	 * 更新分组信息URL: http://localhost:8099/hsim-bservice/team/updateTeamInfo
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/updateTeamInfo",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse updateTeamInfo(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		QueryVerifyReponse resp = new QueryVerifyReponse();
		try {
			//获取前端传过来的数据
			JSONObject object = (JSONObject)request.getAttribute("object");
			Team team = JSON.toJavaObject(object, Team.class);
			System.out.println("【接收到的json】：" + object);
			log.debug("【接收到的json】：" + object);
			
			//不鉴权时获取前端传过来的数据
			/*InputStream is = null;
			is = request.getInputStream();			
			byte bytes[] = new byte[request.getContentLength()];
			is.read(bytes);
			//得到请求中的内容区数据（以CharacterEncoding解码）
			String jsonStr = new String(bytes, "utf-8");
			System.out.println("【接收到的json】：" + jsonStr);
			log.debug("【接收到的json】：" + jsonStr);

			Team team = JSON.toJavaObject(JSON.parseObject(jsonStr), Team.class);*/
			
			//校验好友分组名称不能重复
			boolean teamNameCheck = teamService.teamNameCheck(team);
			if(!teamNameCheck){
				resp.setRetCode(MessageResultEnum.TEAMNAME_DUPLICATE.getRetCode());
				resp.setMessage(MessageResultEnum.TEAMNAME_DUPLICATE.getMessage());
				return resp;
			}
									
			teamService.updateTeamInfo(team);
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			System.out.println("【更新分组信息成功】：" + team.getTeamId());
			log.debug("【更新分组信息成功】：" + team.getTeamId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
		}
       return resp;
	}
	
	/**
	 * 删除分组URL: http://localhost:8099/hsim-bservice/team/deleteTeam
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/deleteTeam",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse deleteTeam(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		QueryVerifyReponse resp = new QueryVerifyReponse();
		try {
			//获取前端传过来的数据
			JSONObject object = (JSONObject)request.getAttribute("object");
			Team team = JSON.toJavaObject(object, Team.class);
			System.out.println("【接收到的json】：" + object);
			log.debug("【接收到的json】：" + object);
			
			//不鉴权时获取前端传过来的数据
			/*InputStream is = null;
			is = request.getInputStream();			
			byte bytes[] = new byte[request.getContentLength()];
			is.read(bytes);
			//得到请求中的内容区数据（以CharacterEncoding解码）
			String jsonStr = new String(bytes, "utf-8");
			System.out.println("【接收到的json】：" + jsonStr);
			log.debug("【接收到的json】：" + jsonStr);

			Team team = JSON.toJavaObject(JSON.parseObject(jsonStr), Team.class);*/
			
			String teamId = team.getTeamId();
			if(teamId != null && !teamId.equals("blacklisted")){
				//删除分组表数据,当删除分组的时候要更新好友表，把放到这个分组里面的好友的分组字段更新为空,两个操作在一个事务中处理
				teamService.deleteTeam(team);
			}
						
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			System.out.println("【删除分组成功】：" + team.getTeamId());
			log.debug("【删除分组成功】：" + team.getTeamId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
		}
       return resp;
	}
	
	/**
	 * 把好友添加到分组中URL: http://localhost:8099/hsim-bservice/team/addFriendIntoTeam
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/addFriendIntoTeam",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse addFriendIntoTeam(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		QueryVerifyReponse resp = new QueryVerifyReponse();
		try {
			//获取前端传过来的数据
			JSONObject object = (JSONObject)request.getAttribute("object");
			Team team = JSON.toJavaObject(object, Team.class);
			System.out.println("【接收到的json】：" + object);
			log.debug("【接收到的json】：" + object);
			
			//不鉴权时获取前端传过来的数据
			/*InputStream is = null;
			is = request.getInputStream();			
			byte bytes[] = new byte[request.getContentLength()];
			is.read(bytes);
			//得到请求中的内容区数据（以CharacterEncoding解码）
			String jsonStr = new String(bytes, "utf-8");
			System.out.println("【接收到的json】：" + jsonStr);
			log.debug("【接收到的json】：" + jsonStr);

			Team team = JSON.toJavaObject(JSON.parseObject(jsonStr), Team.class);*/
			
			/*//组装teamId
			String teamCreator = team.getTeamCreator();
			Date now = new Date(); 
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");//可以方便地修改日期格式
			String dateStr = dateFormat.format(now);
			String teamId = new String(teamCreator + dateStr);
			team.setTeamId(teamId);*/
			if(team.getTeamId().equals("") || team.getTeamId() == null){
				team.setTeamId("unteamed");
			}
			
			//根据user拆分对象
			List<Team> teamList = new ArrayList<Team>();
			String[] friendIdArr = team.getFriendId().split(",");
			for(String friendId : friendIdArr){
				Team teamVo = new Team();
				teamVo.setUserId(team.getUserId());
				teamVo.setFriendId(friendId);
				teamVo.setTeamId(team.getTeamId());
				teamList.add(teamVo);
			}
			teamService.addFriendIntoTeam(teamList);
			//teamService.addFriendIntoTeam(team);
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			System.out.println("【添加好友到分组成功】：" + team.getTeamId());
			log.debug("【添加好友到分组成功】：" + team.getTeamId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
		}
       return resp;
	}
}
